<?php defined('SYSPATH') or die('No direct script access.');
header('X-Frame-Options:deny');
// -- Environment setup --------------------------------------------------------

// Load the core Kohana class
require SYSPATH . 'classes/kohana/core' . EXT;

if (is_file(APPPATH . 'classes/kohana' . EXT))
{
    // Application extends the core
    require APPPATH . 'classes/kohana' . EXT;
}
else
{
    // Load empty core extension
    require SYSPATH . 'classes/kohana' . EXT;
}

/**
 * Set the default time zone.
 *
 * @link http://kohanaframework.org/guide/using.configuration
 * @link http://www.php.net/manual/timezones
 */
//date_default_timezone_set('America/Chicago');
date_default_timezone_set('Asia/Shanghai');

/**
 * Set the default locale.
 *
 * @link http://kohanaframework.org/guide/using.configuration
 * @link http://www.php.net/manual/function.setlocale
 */
setlocale(LC_ALL, 'en_US.utf-8');

/**
 * Enable the Kohana auto-loader.
 *
 * @link http://kohanaframework.org/guide/using.autoloading
 * @link http://www.php.net/manual/function.spl-autoload-register
 */
spl_autoload_register(array('Kohana', 'auto_load'));

/**
 * Optionally, you can enable a compatibility auto-loader for use with
 * older modules that have not been updated for PSR-0.
 *
 * It is recommended to not enable this unless absolutely necessary.
 */
//spl_autoload_register(array('Kohana', 'auto_load_lowercase'));

/**
 * Enable the Kohana auto-loader for unserialization.
 *
 * @link http://www.php.net/manual/function.spl-autoload-call
 * @link http://www.php.net/manual/var.configuration#unserialize-callback-func
 */
ini_set('unserialize_callback_func', 'spl_autoload_call');

/**
 * Set the mb_substitute_character to "none"
 *
 * @link http://www.php.net/manual/function.mb-substitute-character.php
 */
mb_substitute_character('none');

// -- Configuration and initialization -----------------------------------------

/**
 * Set the default language
 */
I18n::lang('ch'); //读取语言包

if (isset($_SERVER['SERVER_PROTOCOL']))
{
    // Replace the default protocol.
    HTTP::$protocol = $_SERVER['SERVER_PROTOCOL'];
}

/**
 * Set Kohana::$environment if a 'KOHANA_ENV' environment variable has been supplied.
 *
 * Note: If you supply an invalid environment name, a PHP warning will be thrown
 * saying "Couldn't find constant Kohana::<INVALID_ENV_NAME>"
 */

//开发模式(Kohana::DEVELOPMENT) or 线上模式(Kohana::PRODUCTION),当项目上线时,应改为线上模式
Kohana::$environment = DEVELOPMENT_MODE ? Kohana::DEVELOPMENT : Kohana::PRODUCTION;
// 设置cookie 多久过期
Cookie::$expiration = 86400;
/**
 * Initialize Kohana, setting the default options.
 *
 * The following options are available:
 *
 * - string   base_url    path, and optionally domain, of your application   NULL
 * - string   index_file  name of your index file, usually "index.php"       index.php
 * - string   charset     internal character set used for input and output   utf-8
 * - string   cache_dir   set the internal cache directory                   APPPATH/cache
 * - integer  cache_life  lifetime, in seconds, of items cached              60
 * - boolean  errors      enable or disable error handling                   TRUE
 * - boolean  profile     enable or disable internal profiling               TRUE
 * - boolean  caching     enable or disable internal caching                 FALSE
 * - boolean  expose      set the X-Powered-By header                        FALSE
 */
//定义目录
$cfg_phone_cmspath = '';
$cfg_mobile_config = require(dirname(DOCROOT) . '/data/mobile.php');
//解析变量
$current_host = $_SERVER['HTTP_HOST'];
$main_host = parse_url($cfg_mobile_config['domain']['main'], PHP_URL_HOST);
$mobile_host = empty($cfg_mobile_config['domain']['mobile']) ? $main_host : parse_url($cfg_mobile_config['domain']['mobile'], PHP_URL_HOST);
if ($main_host == $mobile_host || stripos($mobile_host,'m.'))
{
    $cfg_phone_cmspath = '/phone';
}
//缓存目录,日志目录指定
$cache_dir = CACHE_DIR.'phone';
$logs_dir = LOGS_DIR.'phone';
if(!file_exists($cache_dir))
{
    mkdir($cache_dir,0777,true);
}
if(!file_exists($logs_dir))
{
    mkdir($logs_dir,0777,true);
}


//kohana 初始化
Kohana::init(array(
    'base_url' => $cfg_phone_cmspath . '/',
    'index_file' => '',
    'errors'=> DEVELOPMENT_MODE,
    'cache_dir' => $cache_dir
));


/**
 * Attach the file write to logging. Multiple writers are supported.
 */
Kohana::$log->attach(new Log_File($logs_dir));

Kohana::$log_errors = true;//开启日志记录

/**
 * Attach a file reader to config. Multiple readers are supported.
 */
Kohana::$config->attach(new Config_File);

/**
 * Autoload composer libraries
 */
require BASEPATH . '/vendor/autoload.php';

/**
 * Enable modules. Modules are referenced by a relative or absolute path.
 */
$default_modules=array(
    'excaptha'=> BASEPATH.'/plugins/excaptha',
    'developer' => BASEPATH.'/plugins/developer',
    // 'auth'       => MODPATH.'auth',       // Basic authentication
    'cache'      => MODPATH.'cache',      // Caching with multiple backends
    // 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
    'database' => MODPATH . 'database',   // Database access
    'image' => MODPATH . 'image',      // Image manipulation
    // 'minion'     => MODPATH.'minion',     // CLI Tasks
    'orm' => MODPATH . 'orm',       // Object Relationship Mapping
    'pagination' => MODPATH . 'pagination', //分页
    'cron' => MODPATH .'cron',//任务类
    'captcha' => MODPATH . 'captcha',//验证码类
    'hooks' => MODPATH. 'hooks',//事件类
    // 'unittest'   => MODPATH.'unittest',   // Unit testing
    // 'userguide'  => MODPATH.'userguide' // User guide and API documentation
);
$plugins_modules = include(BASEPATH.'/data/module.php');
foreach($plugins_modules as $plugin_key=>$plugin)
{
    $plugins_modules[$plugin_key] = BASEPATH.$plugin;
}
$default_modules =is_array($plugins_modules)?array_merge($default_modules,$plugins_modules):$default_modules;
Kohana::modules($default_modules);


/**
 * Set the routes. Each route must have a minimum of a name, a URI and a set of
 * defaults for the URI.
 */

require(APPPATH . 'route.php');
$cfg_basehost = St_Functions::get_http_prefix() . $_SERVER['HTTP_HOST']; //网站域名
$cfg_default_templet = '/default/';
$cfg_public_url = $cfg_phone_cmspath . '/public/';
extract(Common::cache_config(),EXTR_OVERWRITE);
//手机版系统信息写入缓存
extract(Common::cache_config());
//子站判断与处理
Common::cache_web_list();
//主站点webid
$sys_webid = 0;
//主站点prefix
$sys_prefix = Common::get_main_prefix();
//Cookie设置
Cookie::$httponly=true;
Cookie::$salt = 'stourwebcms';
cookie::$path = '/';
Cookie::$domain = Common::cookie_domain();

//加载事件配置文件
Hook::load();
//任务初始化
St_Task::init();

$saas_xcx = include(BASEPATH . '/data/saas_xcx.php');
//0：关闭pc站点
if(isset($saas_xcx['phone']) && $saas_xcx['phone'] == 0)
{
    $xcx_go = false;
    $pass_item = array(
        array(
            'execute_url'=> 'api/v2' // uniapp程序接口
        ),
        array(
            'execute_url'=> 'api/standard' // 小程序接口
        ),
        array(
            'execute_url'=> 'connect/' // 智旅互联
        )

    );
    foreach($pass_item as $ev)
    {
        if(strpos($_SERVER['REQUEST_URI'],$ev['execute_url'])){
            $xcx_go = true;
        }
    }
    if(!$xcx_go)
    {
        $content = Model_Sysconfig::get_configs(0,'mobile_close_content',true);
        exit('<meta charset="utf-8"><p align="center">'.$content.'</p>');
    }
}


//新版与老版移动端选择判断 1为老版,2为新版
/*if($cfg_m_version == '2')
{
    $payset_go = false;
    // 跳过支付页面
    $paysets = DB::select("pinyin")->from("payset")->execute()->as_array();
    foreach($paysets as $ev)
    {
        if(strpos($_SERVER['REQUEST_URI'],$ev['pinyin']))
        {
            $payset_go = true;
        }
    }
    if(!$payset_go)
    {
        $redirect_mobile_url = $cfg_mobile_config['domain']['main'] ? $cfg_mobile_config['domain']['main'] : $cfg_basehost;
        header("Location:" . $redirect_mobile_url . '/h5');
        exit;
    }
}*/


//子站检测
if (file_exists(CACHE_DIR . 'v5/weblist.php'))
{
    require_once CACHE_DIR . 'v5/weblist.php';
    $url = $_SERVER['HTTP_HOST'];//当前域名
    $uarr = explode('.', $url);
    $prefix = $uarr[0]; //当前域名前辍
    if (array_key_exists($prefix, $weblist))
    {
        //重置当前webid,prefix
        $sys_webid = $weblist[$prefix]['webid'];
        $sys_prefix = $prefix;
    }
}

//站点跳转
if ($current_host != $mobile_host)
{
    //兼容性修复
    $uri = $_SERVER["HTTP_X_REWRITE_URL"];
    if ($uri == null)
    {
        $uri = $_SERVER["REQUEST_URI"];
    }
    $request_uri = preg_replace('~\/?phone\/?~', '', $uri);
    $prefix = '/';
    if ($sys_webid != 0 && strpos($request_uri,'show_')!==false)
    {
        $prefix = "/{$sys_prefix}/";
    }

    //判断手机域名与主域名是否相等
    if($cfg_mobile_config['domain']['mobile'] != $cfg_mobile_config['domain']['main'])
    {
        $current_url = rtrim($cfg_mobile_config['domain']['mobile'],'/') . $prefix.$request_uri;
    }
    else
    {
        $current_url = rtrim($cfg_mobile_config['domain']['main'],'/') .'/phone'. $prefix. $request_uri;
    }
    header("Location:".$current_url);
    exit;
}

if(St_Functions::is_normal_app_install('mobiledistribution'))
{
    Model_Fenxiao::save_fxcode();
}
